package com.kfyty.auto.host.service;

import com.kfyty.auto.host.api.HostSearchApi;
import com.kfyty.auto.host.utils.Cmd;
import com.kfyty.loveqq.framework.core.autoconfig.annotation.Autowired;
import com.kfyty.loveqq.framework.core.autoconfig.annotation.Service;
import com.kfyty.loveqq.framework.core.exception.ResolvableException;
import com.kfyty.loveqq.framework.core.lang.ConstantConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

@Slf4j
@Service
public class HostService {
    @Autowired
    private HostSearchApi hostSearchApi;

    public String findAnyIp(String host) {
        List<String> search = this.hostSearchApi.search(host);
        for (String ip : search) {
            if (Cmd.ping(ip)) {
                return ip;
            }
        }
        throw new ResolvableException("Can't find any ip for host: " + host);
    }

    public void writeToHosts(String host, String ip, String hostPath) {
        File hosts = new File(hostPath, "hosts");
        File file = Cmd.copy(hosts, new File(ConstantConfig.TEMP_PATH));

        String line = null;
        StringBuilder builder = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
             FileOutputStream output = new FileOutputStream(hosts)) {

            while ((line = reader.readLine()) != null) {
                log.info("read line: {}", line);
                if (line.contains(host)) {
                    continue;
                }
                builder.append(line).append(System.lineSeparator());
            }

            builder.append(ip).append("\t\t").append(host).append(System.lineSeparator());

            output.write(builder.toString().getBytes());
            output.flush();
        } catch (IOException e) {
            throw new ResolvableException(e);
        } finally {
            boolean delete = file.delete();
        }
    }
}
